<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\User;

use App\Dao\CouponDao;

use App\Dao\CouponPaymentDao;
use App\Dao\UserCouponDao;
use App\Exception\CustomException;
use App\Service\Service;
use App\Service\UploadService;
use Endroid\QrCode\QrCode;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Snowflake\IdGeneratorInterface;

/**
 * 优惠券服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\Admin
 */
class OrderCouponService extends Service
{
    /**
     * @Inject
     * @var UserCouponDao
     */
    private $dao;

    /**
     * @Inject
     * @var CouponPaymentDao
     */
    private $coupon_payment_dao;

    /**
     * @Inject
     * @var CouponDao
     */
    private $coupon_dao;

    /**
     * @Inject
     * @var UploadService
     */
    private $Upload;

    /**
     * 订单状态：已关闭
     *
     * @var int
     */
    const STATUS_CLOSE = 5;

    /**
     * 图片保存路径
     *
     *@var string
     */
    public $path = "/home/wwwroot/default/hyperf/hyperf/app/";
    /**
     * 立即下单
     * @param array $params
     * @return mixed
     */
    public function buy( array $params )
    {
        $order_no = (string)$this->container->get(IdGeneratorInterface::class)->generate();

        $coupon = $this->coupon_dao->getCouponByMap([
            'id' => $params['coupon_id']
        ]);

        $data = [
            'order_no' => $order_no,
            'coupon_id' => $params['coupon_id'],
            'business_id' => $coupon['business_id'],
            'user_id' => uid(),
            'type' => $params['type'],
            'status' => $this->dao::STATUS_UNPAID,
            'total_price' => $coupon['goods_price'],
            'price' => $coupon['price'],
            'discount_price' => ($coupon['goods_price'] - $coupon['price']),
            'expire_time' => strtotime($coupon['expire_time']),
            'buy_time' => time(),
            'created_at' => time(),
            'updated_at' => time()
        ];

        $result = $this->dao->create($data);
        !$result && $this->error();
        return [
            'order_no' => $order_no,
            'price' => $coupon['price'],
        ];
    }

    /**
     * 优惠券支付
     * @param string $order_no
     * @param string $pay_type
     * @return
     */
    public function pay(string $order_no, string $pay_type)
    {
        $order = $this->dao->first([
            'order_no' => $order_no,
            'user_id' => uid()
        ]);


        // 获取商品
        if (!$coupon = $order->coupon)  $this->error();


        // 已支付
        if ($order->status === $this->dao::STATUS_PAID) {
            $this->error('ORDER.ORDER_PAID');
        }

        // 订单是否需要支付
        if ($order->price <= 0) {
            $this->error('ORDER.NOT_REQUIRED_PAY');
        }

        // 非待支付状态无法进行付款
        if ($order->status !== $this->dao::STATUS_UNPAID) {
            $this->error('ORDER.STATUS_EXCEPTION');
        }

        //获取二维码
        $qr_code = $this->getQrCode($order_no);

        $order->pay_type = $pay_type;
        $order->pay_time = time();
        $order->qr_code = $qr_code;
        if (!$order->save()) {
            throw new CustomException('ORDER.UPDATE_FAIL');
        }

        return [
            'user_id' => uid(),
            'value' => $order_no,
            'amount' => (float)$order->price,
            'title' => $coupon->title,
            'type' => 1,
        ];
    }

    /**
     * 关闭优惠券订单
     *
     * @author 张昊(2396675557@qq.com)
     * @param string $order_no
     * @param int $status
     * @param string $remark
     */
    public function closeOrder(string $order_no, int $status, string $remark = '')
    {
        Db::beginTransaction();
        try {
            $order = $this->dao->first([
                'order_no' => $order_no
            ]);
            if (!$order) throw new CustomException('ORDER.NOT_EXIST');
            if ($order->status !== $this->dao::STATUS_UNPAID) throw new CustomException('ORDER.STATUS_EXCEPTION');
            $order->status = $status;
            $order->remark = $remark;
            if (!$order->save()) {
                throw new CustomException('ORDER.UPDATE_FAIL');
            }
            Db::commit();
        }
        catch (CustomException $e) {
            Db::rollBack();
            $this->logger('order')->error($e->getMessage(), ['closeOrder']);
            $this->error('');
        }
        catch (\Exception $e) {
            Db::rollBack();
            $this->error('COMMON.SYSTEM_ERROR');
        }
    }

    /**
     * 生成二维码
     * @param $content
     * @return string
     */
    public function getQrCode( $content )
    {
        $qrCode = new QrCode($content);//开启二维码

        $path_name = $this->path.'/public/images/'.rand(10000, 99999).'.png'; //路径

        $qrCode->writeFile($path_name); //生成二维码

        $file_name = md5_file($path_name).'.png'; //生成图片名称

        $return = $this->Upload->qrCodeUpload($path_name, $file_name); //上传oss

        unlink($path_name);
        return $return;

    }

    /**
     * ping++ 优惠券回调
     *
     * @param array $params
     */
    public function pingNotify(array $params)
    {
        $where['status'] = $this->dao::STATUS_UNPAID;
        $where['pay_no'] = substr($params['order_no'],6);
        $payment = $this->coupon_payment_dao->find($where);
        $payment->trade_no = $params['transaction_no'];
        $payment->status = $this->dao::STATUS_PAID;
        $payment->updated_at = time();
        if( $payment->save() ) {
            $order_where['status'] = $this->dao::STATUS_UNPAID;
            $order_where['order_no'] = $payment['value'];
            $coupon_order = $this->dao->find($order_where);
            $coupon_order->status = $this->dao::STATUS_PAID;
            $coupon_order->pay_time = time();
            $coupon_order->buy_time = time();
            $coupon_order->updated_at = time();
            $coupon_order->save();

        } else {
            $this->logger('payment')->info("回调失败");
        }
    }

}